import _ from 'lodash';

const mixdate = {
  data() {
    return {
      firstDateProp: '',
      secondDateProp: '',
      dateUnit: '',
      dateOptions: [
        {
          value: 'year',
          label: '年'
        },
        {
          value: 'month',
          label: '月'
        },
        {
          value: 'week',
          label: '周'
        },
        {
          value: 'day',
          label: '天'
        },
        {
          value: 'hour',
          label: '时'
        },
        {
          value: 'minute',
          label: '分'
        },
        {
          value: 'second',
          label: '秒'
        }
      ]
    };
  },
  watch: {
    dateUnit(value) {
      const obj = _.filter(this.dateOptions, { value });
      if (obj.length) {
        this.showContent = this.showContent.replace(
          /\(\W\)/g,
          `(${obj[0].label})`
        );
      }
    }
  },
  mounted() {
    const { firstDateProp, secondDateProp, dateUnit } = this.item;
    if (firstDateProp) {
      this.firstDateProp = firstDateProp;
    }
    if (secondDateProp) {
      this.secondDateProp = secondDateProp;
    }
    if (dateUnit) {
      this.dateUnit = dateUnit;
    }
  },
  methods: {
    filterDateOptions(type) {
      this.dateOptions.forEach((item) => {
        if (item.value === type) {
          item.disabled = false;
        } else {
          item.disabled = true;
        }
      });
    },
    setType(type) {
      let itemType = '';
      switch (type) {
        case 'date':
          itemType = 'day';
          break;
        case 'daterange':
          itemType = 'day';
          break;
        case 'timerange':
          itemType = 'second';
          break;
        case 'datetimerange':
          itemType = 'second';
          break;
        case 'datetime':
          itemType = 'second';
          break;
        default:
          itemType = type;
      }
      this.filterDateOptions(itemType);
      return itemType;
    },
    getDateLabel(prop, isSetType = false, cols = this.cols) {
      let labelsStr = '';
      let type = '';
      if (!prop) {
        return labelsStr;
      }

      const props = prop.split('.');
      const item = _.filter(cols, { prop: props[0] })[0];

      labelsStr += item?.label || '';
      if (item?.type && isSetType) {
        let itemType = this.setType(item.type);
        this.dateUnit = itemType;
        type = itemType;
      }
      if (item?.column) {
        const itemChild = _.filter(item.column, { prop: props[1] })[0];
        labelsStr += `.${itemChild.label}`;
        if (isSetType) {
          let itemType = this.setType(itemChild.type);
          this.dateUnit = itemType;
          type = itemType;
        }
      }
      return {
        str: labelsStr,
        type
      };
    }
  }
};

export default mixdate;
